package initialize

import (
	"authserver/global"
	"encoding/json"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

// 初始化数据库并产生数据库全局变量

func Mysql() {

	username := global.GVA_CONFIG.Mysql.Username
	pwd := global.GVA_CONFIG.Mysql.Password
	host := global.GVA_CONFIG.Mysql.Path
	dbName := global.GVA_CONFIG.Mysql.Dbname

	Default := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
		SlowThreshold:             200 * time.Millisecond, // 慢sql阈值，200ms
		LogLevel:                  logger.Info,            // 日志输出级别
		IgnoreRecordNotFoundError: false,                  // 不忽略记录不存在的错误
		Colorful:                  true,                   // 彩色输出日志
	})

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", username, pwd, host, dbName)
	fmt.Println(dsn)
	if db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: Default,
	}); err != nil {
		global.GVA_LOG.Error("MsSQL启动异常", err)
		os.Exit(0)
	} else {
		global.GVA_DB = db
		bs, _ := json.Marshal(db.Config)
		fmt.Println(string(bs))
	}
}
